<script setup lang="ts">
import { getConsultOrderPre, getPatientDetail, createConsultOrder } from '@/services/consult'
import { useConsultStore } from '@/stores'
import type { ConsultOrderPreData } from '@/types/consult';
import type { Patient } from '@/types/user';
import { error } from '@/utils/tools';
import { showConfirmDialog, showDialog } from 'vant'
import 'vant/es/dialog/style'
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter, onBeforeRouteLeave } from 'vue-router'
const store = useConsultStore()
const router = useRouter()
const checkedColor = 'var(--cp-primary)'
// 预支付数据
const payInfo = ref<ConsultOrderPreData>()
// 拉取预支付信息
const loadPreData = async () => {
  const res = await getConsultOrderPre({ type: store.consult.type, illnessType: store.consult.illnessType })
  payInfo.value = res.data
  // 记录已经使用的优惠券id(假设有)
  store.setCouponId(payInfo.value.couponId)
}

// 获取患者详情数据
const patient = ref<Patient>()
const loadPatient = async () => {
  if (!store.consult.patientId) return
  const res = await getPatientDetail(store.consult.patientId)
  patient.value = res.data
}

onMounted(() => {
  // 4.用户刷新时让用户问诊记录页面
  const { type, illnessType, depId } = store.consult
  if (!type || !depId || !illnessType) {
    return showDialog({
      title: '温馨提示',
      message: '问诊信息不完整请重新填写，如有未支付的问诊订单可在问诊记录中继续支付',
      closeOnPopstate: false
    }).then(() => {
      router.push('/')
    })
  }
  loadPreData()
  loadPatient()
})


// 支付流程
// 是否同意支付协议
const agree = ref(false)
// 1.点击立即支付创建订单
// 2.选择支付方式
// 控制抽屉的显示和隐藏
const show = ref(false)
// const paymentMethod = ref<0 | 1>()
const loading = ref(false)
// 订单id
const orderId = ref('')
const submit = async () => {
  if (!agree.value) return error('请勾选我已同意支付协议')
  // 创建订单
  loading.value = true
  const res = await createConsultOrder(store.consult)
  orderId.value = res.data.id
  loading.value = false
  // 清除原来pinia保存的该问诊数据
  store.clearConsult()
  // 打开支付方式的抽屉
  show.value = true
}

// 目的：想法设法让患者付款
// 1.关闭抽屉的关闭的按钮
// 2.点其他方式关闭时，要让用户做选择
const onClose = () => {
  return showConfirmDialog({
    title: '关闭支付',
    message: '取消支付将无法获得医生回复，医生接诊名额有限，是否确认关闭？',
    cancelButtonText: '仍要关闭',
    confirmButtonText: '继续支付',
    confirmButtonColor: 'var(--cp-primary)'
  }).then(() => {
    // 继续支付
    return false
  }).catch(() => {
    // 仍要关闭，让它跳转到问诊记录页面，里面能看到所有的问诊记录订单，还可以让用户支付
    // orderId清空，避免下面的路由导航阻止路由的回退行为
    orderId.value = ''
    router.push('/user/consult')
    return true
  })
}
// 3.一旦产生了订单就不允许用户后退
onBeforeRouteLeave(() => {
  if (orderId.value) return false
})

// 4.发起支付
/* const payCallback = 'http://localhost:3000/room'
const pay = async () => {
  if (paymentMethod.value === undefined) return error('请先选择支付方式')
  const params = {
    paymentMethod: paymentMethod.value,
    orderId: orderId.value,
    payCallback
  }
  try {
    const { data } = await getConsultOrderPayUrl(params)
    // 正常要跳转到支付地址
    location.href = data.payUrl
  } catch {
    // 支付接口异常：直接跳到支付成功的回跳页面
    location.href = `${payCallback}?orderId=${orderId.value}&payResult=true&type=2`
  }
} */

// 支付地址
const payCallback = import.meta.env.VITE_API_URL



</script>

<template>
  <div class="consult-pay-page">
    <cp-nav-bar title="支付" />
    <!-- 支付头部信息 -->
    <div class="pay-info" v-if="payInfo">
      <p class="tit">图文问诊 {{ payInfo.payment }} 元</p>
      <img class="img" src="@/assets/avatar-doctor.svg" />
      <p class="desc">
        <span>极速问诊</span>
        <span>自动分配医生</span>
      </p>
    </div>
    <!-- 支付信息 -->
    <van-cell-group v-if="payInfo">
      <van-cell title="优惠券" :value="`-¥${payInfo.couponDeduction}`" />
      <van-cell title="积分抵扣" :value="`-¥${payInfo.pointDeduction}`" />
      <van-cell title="实付款" :value="`¥${payInfo.actualPayment}`" class="pay-price" />
    </van-cell-group>
    <div class="pay-space"></div>
    <!-- 患者信息 -->
    <van-cell-group v-if="patient">
      <van-cell title="患者信息" :value="`${patient.name} | ${patient.genderValue} | ${patient.age}岁`"></van-cell>
      <van-cell title="病情描述" :label="store.consult.illnessDesc"></van-cell>
    </van-cell-group>
    <div class="pay-schema" v-if="payInfo && patient">
      <van-checkbox v-model="agree" :checked-color="checkedColor">我已同意 <span class="text">支付协议</span></van-checkbox>
    </div>
    <!-- 支付方式的抽屉组件 -->
    <cp-pay-sheet v-if="payInfo" :order-id="orderId" :actual-payment="payInfo.actualPayment" v-model:show="show"
      :pay-callback="payCallback" :on-close="onClose"></cp-pay-sheet>
    <!--  <van-action-sheet :before-close="onClose" :closeable="false" v-model:show="show" title="选择支付方式" v-if="payInfo"
      :close-on-popstate="false">
      <div class="pay-type">
        <p class="amount">￥{{ payInfo.actualPayment.toFixed(2) }}</p>
        <van-cell-group>
          <van-cell title="微信支付" @click="paymentMethod = 0">
            <template #icon><cp-icon name="consult-wechat" /></template>
            <template #extra><van-checkbox :checked-color="checkedColor" :checked="paymentMethod === 0" /></template>
          </van-cell>
          <van-cell title="支付宝支付" @click="paymentMethod = 1">
            <template #icon><cp-icon name="consult-alipay" /></template>
            <template #extra><van-checkbox :checked-color="checkedColor" :checked="paymentMethod === 1" /></template>
          </van-cell>
        </van-cell-group>
        <div class="btn">
          <van-button type="primary" round block @click="pay">立即支付</van-button>
        </div>
      </div>
    </van-action-sheet> -->

    <!-- 按钮 -->
    <van-submit-bar v-if="payInfo" button-type="primary" :price="payInfo.actualPayment * 100" button-text="立即支付"
      text-align="left" @click="submit" :loading="loading" />
  </div>
</template>

<style lang="scss" scoped>
.consult-pay-page {
  padding: 46px 0 50px 0;

  // 支付信息
  .pay-info {
    display: flex;
    padding: 15px;
    flex-wrap: wrap;
    align-items: center;

    .tit {
      width: 100%;
      font-size: 16px;
      margin-bottom: 10px;
    }

    .img {
      margin-right: 10px;
      width: 38px;
      height: 38px;
      border-radius: 4px;
      overflow: hidden;
    }

    .desc {
      flex: 1;

      >span {
        display: block;
        color: var(--cp-tag);

        &:first-child {
          font-size: 16px;
          color: var(--cp-text2);
        }
      }
    }
  }

  .pay-price {
    ::v-deep() {
      .vam-cell__title {
        font-size: 16px;
      }

      .van-cell__value {
        font-size: 16px;
        color: var(--cp-price);
      }
    }
  }

  .pay-space {
    height: 12px;
    background-color: var(--cp-bg);
  }

  // 患者信息

  .pay-schema {
    height: 56px;
    display: flex;
    align-items: center;
    justify-content: center;

    .text {
      color: var(--cp-primary);
    }
  }

  // 底部
  :deep() {
    .van-submit-bar__button {
      font-weight: normal;
      width: 160px;
      background-color: var(--cp-primary);
      border-color: var(--cp-primary);
    }

    .van-cell {
      padding: 15px;
    }
  }

}
</style>